import React from 'react';
import type { IMessageConfigProps } from '../type';
import { useRequest } from 'umi';
import {
  associateOneWechatTemplateMsg,
  changeTemplateState,
  getWechatTemplateMsgList,
  sendWechatTemplateMsg,
} from './service';
import { BugOutlined, EditOutlined } from '@ant-design/icons';
import { Space, Steps, Switch, Typography, message } from 'antd';
import type { IWechatTemplateMsg } from './type';
import {
  ModalForm,
  ProFormGroup,
  ProFormList,
  ProFormText,
  ProCard,
} from '@ant-design/pro-components';
import { nanoid } from 'nanoid';
import { FieldNameMap } from '../constant';

import './index.less';

const { Title, Text, Paragraph } = Typography;
const { Step } = Steps;

const WechatMsgConfig: React.FC<IMessageConfigProps> = (props) => {
  const { ifConfig = false } = props;
  const {
    data = [],
    loading,
    refresh,
  } = useRequest(async () => {
    const res = await getWechatTemplateMsgList();
    return res;
  });

  return (
    <Space direction="vertical" size={'large'}>
      {ifConfig && (
        <ProCard
          title={'模板配置步骤'}
          bordered
          subTitle={
            <a href={'https://www.bilibili.com'} target="blank">
              操作指引
            </a>
          }
        >
          <Steps style={{ margin: '20px 8px' }}>
            <Step
              title="步骤一"
              description="微信公众号管理员去微信公众平台设置好指定的服务类目"
              status="process"
            />
            <Step
              title="步骤二"
              description="前往微信公众平台模板消息页面找到类目模板，搜索指定的模板标题并按照指定模板详情配置好"
              status="process"
            />
            <Step
              title="步骤三"
              description="进入配置好的类目模板页面详情，将模板生成的关键词和模板ID配置到收费平台"
              status="process"
            />
            <Step
              title="步骤四"
              description="点击测试按钮输入测试手机号测试配置是否生效"
              status="process"
            />
          </Steps>
        </ProCard>
      )}
      <ProCard title="微信公众号模板消息" gutter={[16, 16]} wrap>
        {data.map((item: IWechatTemplateMsg) => (
          <ProCard
            key={item.title}
            title={item.title}
            bordered
            hoverable
            extra={
              ifConfig && (
                <Switch
                  checked={item.enable}
                  checkedChildren="启用"
                  unCheckedChildren="禁用"
                  defaultChecked={item.enable}
                  onClick={async (checked: boolean) => {
                    const res = await changeTemplateState(item.template_id, checked);
                    if (res && res.success) {
                      message.success(res.message);
                    } else {
                      message.error(res.message);
                    }
                    refresh();
                  }}
                />
              )
            }
            loading={loading}
            actions={[
              ifConfig && (
                <ModalForm<IWechatTemplateMsg>
                  title={'配置模板消息'}
                  width={600}
                  trigger={
                    <div
                      style={{
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center',
                        padding: 12,
                        flex: 1,
                        gap: 8,
                      }}
                    >
                      <EditOutlined key="edit" />
                      编辑
                    </div>
                  }
                  submitTimeout={1000}
                  onFinish={async (values) => {
                    const res = await associateOneWechatTemplateMsg({
                      ...values,
                      title: item.title,
                    });
                    if (res.success) {
                      message.success('关联成功');
                    } else {
                      message.error(res.message);
                    }
                    refresh();
                    return true;
                  }}
                >
                  <ProFormText
                    name="template_id"
                    label="模板ID"
                    placeholder="请输入模板ID"
                    initialValue={item.template_id}
                    rules={[{ required: true, message: '这是必填项' }]}
                  />
                  <ProFormList
                    name="template_details"
                    label="模板详情"
                    initialValue={item.template_details}
                    creatorButtonProps={false}
                    deleteIconProps={false}
                    copyIconProps={false}
                  >
                    <ProFormGroup>
                      <ProFormText
                        name="field_name"
                        label="字段名称"
                        placeholder={'请选择字段名称'}
                        disabled
                        rules={[{ required: true, message: '请输入字段名称' }]}
                      />
                      <ProFormText
                        name="field_map_id"
                        label="字段关联ID"
                        placeholder={'字段关联ID'}
                        rules={[{ required: true, message: '请输入字段关联ID' }]}
                      />
                    </ProFormGroup>
                  </ProFormList>
                </ModalForm>
              ),
              ifConfig && (
                <ModalForm<{
                  plateNumber: string;
                  url?: string;
                }>
                  title={'测试模板消息'}
                  width={500}
                  trigger={
                    <div
                      style={{
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center',
                        padding: 12,
                        gap: 8,
                        flex: 1,
                      }}
                    >
                      <BugOutlined key="test" />
                      调试
                    </div>
                  }
                  submitTimeout={1000}
                  onFinish={async (values) => {
                    const final_data: Record<string, string> = {};
                    item.template_details.map(
                      (i) => (final_data[i.field_id] = FieldNameMap.get(i.field_id) || ''),
                    );
                    const res = await sendWechatTemplateMsg({
                      plateNumber: values.plateNumber,
                      type: item.title,
                      url: values.url,
                      content: final_data,
                    });
                    if (res.success) {
                      message.success('发送成功，请去公众号查看');
                      return true;
                    } else {
                      message.error(res.message);
                      return false;
                    }
                  }}
                >
                  <ProFormText
                    name="plateNumber"
                    label="车牌号码"
                    placeholder="请输入接收者绑定的车牌号码"
                    validateFirst={true}
                    rules={[
                      { required: true, message: '这是必填项' },
                      {
                        validator: async (_, value) => {
                          const reg = new RegExp(
                            /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-Z0-9]{4}[A-Z0-9挂学警港澳]{1}$/,
                          );
                          if (!reg.test(value)) {
                            return Promise.reject('车牌号码格式错误');
                          } else {
                            return Promise.resolve();
                          }
                        },
                      },
                    ]}
                  />
                  <ProFormText name="url" label="跳转链接" placeholder="请输入跳转链接（可选）" />
                </ModalForm>
              ),
            ]}
            type="inner"
            wrap
            colSpan={{ xs: 24, sm: 24, md: 24, lg: 12, xl: 12, xxl: 8 }}
          >
            <ProCard>
              <Space direction="vertical" style={{ whiteSpace: 'nowrap' }}>
                <Space align="baseline">
                  <Title level={5}>模板ID：</Title>
                  <Text>{item.template_id}</Text>
                </Space>
                <Space align="baseline">
                  <Title level={5}>标题：</Title>
                  <Text>{item.title}</Text>
                </Space>
                <Space align="baseline">
                  <Title level={5}>类型：</Title>
                  <Text>{item.template_type}</Text>
                </Space>
              </Space>
            </ProCard>
            <ProCard title="模板预览示例" type="inner" bordered style={{ minWidth: 300 }}>
              {item.template_details &&
                item.template_details.map(
                  (i: { field_name: string; field_id: string; field_map_id: string }) => (
                    <Paragraph key={nanoid()}>{`${i.field_name}：{{${
                      i.field_map_id || '待配置'
                    }.DATA}}`}</Paragraph>
                  ),
                )}
            </ProCard>
          </ProCard>
        ))}
      </ProCard>
    </Space>
  );
};

export default WechatMsgConfig;
